﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using EbbinghausWord.DAL;
using EbbinghausWord.Entities;

namespace EbbinghausWord.BLL
{
    /// <summary>
    /// 存储管理类
    /// </summary>
    public static class StoreManager
    {
        #region private field

        private static readonly IsolatedStorageFile _solatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();

        #endregion

        #region 单词本管理
        /// <summary>
        /// 用户个人单词本 存储到 独立存储中
        /// </summary>
        public static void SaveUserWordbook()
        {
            WordBookManager.WordBook.SaveUserWordBookFile(SystemConfig.UserWordkBookFileName);
        }

        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <returns></returns>
        public static bool IsFileExist(string fileName)
        {
            return _solatedStorageFile.FileExists(fileName);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void DeleteFile(string fileName)
        {
            _solatedStorageFile.DeleteFile(fileName);
        }

        /// <summary>
        /// 返回文件最后修改时间
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static DateTimeOffset GetFileLastWriteTime(string fileName)
        {
            return _solatedStorageFile.GetLastWriteTime(fileName);
        }

        /// <summary>
        /// 保存用户单词本文件，每次保存创建新文件，而不是覆盖旧文件
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="fileName"></param>
        public static void SaveUserWordBookFile<T>(this IEnumerable<T> collection, string fileName)
        {
            var fileStream = _solatedStorageFile.OpenFile(fileName, FileMode.Create,
                                                          FileAccess.ReadWrite);
            var streamWriter = new StreamWriter(fileStream);
            var sb = new StringBuilder();
            
            foreach (var t in collection)
            {
                sb.AppendLine(t.ToString());
                //只加一个就行了
                break;
            }
            streamWriter.Write(sb.ToString());
            streamWriter.Close();
            fileStream.Close();
        }

        /// <summary>
        /// 打开文件
        /// </summary>
        public static List<WordEntity> OpenFile(string fileName)
        {
            var fileStream = _solatedStorageFile.OpenFile(fileName, FileMode.OpenOrCreate,
                                                          FileAccess.ReadWrite);
            var streamReader = new StreamReader(fileStream);
            var userWords = new List<WordEntity>();

            //打开词典
            //var dictionary = DictionaryManager.GetWordDictionary();

            while (true)
            {
                //获取一个用户单词的字符串
                var entityString = streamReader.ReadLine();
                if (entityString == null) break;
                try
                {
                    //获取单词记忆信息
                    userWords.Add(WordEntity.CreateEntityFromString(entityString));
                }
                catch (Exception)
                {
                    MessageBox.Show("ErrorLine : " + entityString);
                }
            }
            fileStream.Close();

            //获取单词含义
            //userWords.ForEach(x =>
            //{
            //    try
            //    {
            //        var word = DictionaryManager.GetWord(x.English);
            //        x.Chinese = word.Chinese;
            //        x.Soundmark = word.Soundmark;
            //    }
            //    catch (Exception)
            //    {
            //        Tools.ShowMessage(x.English + "在词典中不存在！");
            //    }

            //});

            return userWords;
        }


        /// <summary>
        /// 复制数据库文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void CopyDBFile(string fileName)
        {
            using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isolatedStorageFile.FileExists(fileName)) return;

                //文件不存在则copy
                using (var destfs = isolatedStorageFile.CreateFile(fileName))
                {
                    var fs = Application.GetResourceStream(
                        new Uri("/EbbinghausWord;component/words/" + fileName, UriKind.Relative)).Stream;
                    var bt = new byte[fs.Length];

                    fs.Read(bt, 0, (int)fs.Length);
                    destfs.Write(bt, 0, (int)fs.Length);
                }
            }
        }


        /// <summary>
        /// 复制数据库文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="isOverride"> </param>
        public static void CopyDBFile(string fileName, bool isOverride)
        {
            //using (var userDb = new UserDataContext())
            //{
            //    if (userDb.DatabaseExists())
            //    {
            //        userDb.DeleteDatabase();
            //    }
            //}

            CopyDBFile(fileName);
        }

        /// <summary>
        /// 生成发音文件数据库
        /// </summary>
        //public static void CreateVoiceDB()
        //{
        //    using (var voiceDB = new VoiceDataContext())
        //    {
        //        if (!voiceDB.DatabaseExists())
        //        {
        //            voiceDB.CreateDatabase();
        //        }
        //    }
        //}
        #endregion


    }
}
